package juc.mysynchronized.semaphore;

/**
 * @ClassName DatabaseConnectionPool
 * @PackageName juc.mysynchronized.semaphore
 * @projectName myThread
 * @Description TODO
 * @Author games
 * @Date 2025/9/4 下午4:37
 * @Version 1.0
 */
import java.util.concurrent.Semaphore;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class DatabaseConnectionPool {
    private final Semaphore connectionSemaphore;
    private final int maxConnections;

    public DatabaseConnectionPool(int maxConnections) {
        this.maxConnections = maxConnections;
        this.connectionSemaphore = new Semaphore(maxConnections);
    }

    public void useConnection() {
        try {
            // 获取数据库连接许可
            connectionSemaphore.acquire();
            System.out.println(Thread.currentThread().getName() +
                    " 获取数据库连接，剩余许可: " + connectionSemaphore.availablePermits());

            // 模拟数据库操作
            Thread.sleep(2000);

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            // 释放数据库连接许可
            connectionSemaphore.release();
            System.out.println(Thread.currentThread().getName() +
                    " 释放数据库连接，剩余许可: " + connectionSemaphore.availablePermits());
        }
    }

    public static void main(String[] args) {
        DatabaseConnectionPool pool = new DatabaseConnectionPool(3);
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 模拟5个线程同时请求数据库连接，但连接池只有3个连接
        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            executor.submit(() -> {
                System.out.println("任务 " + taskId + " 请求数据库连接");
                pool.useConnection();
                System.out.println("任务 " + taskId + " 完成数据库操作");
            });
        }

        executor.shutdown();
    }
}

